from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, List, Dict, Any
from pydantic import BaseModel
from sqlalchemy.orm import Session
from core.database import get_db
from services.petition_ledger_service import PetitionLedgerService
from core.auth import get_current_active_user
from models.user import User

router = APIRouter()

class PetitionLedgerSearchRequest(BaseModel):
    """信访台账搜索请求模型"""
    page: int = Query(1, ge=1, description="页码")
    page_size: int = Query(20, ge=1, le=100, description="每页条数")
    region: Optional[str] = Query(None, description="所在区域")
    petitioner_name: Optional[str] = Query(None, description="来信人姓名")
    respondent_unit: Optional[str] = Query(None, description="被投诉单位")
    analysis_status: Optional[str] = Query(None, description="分析状态")
    date_from: Optional[str] = Query(None, description="开始日期")
    date_to: Optional[str] = Query(None, description="结束日期")
    sentiment_type: Optional[str] = Query(None, description="情感类型")
    complaint_type: Optional[str] = Query(None, description="投诉类型")
    task_id: Optional[int] = Query(None, description="分析任务ID")

class PetitionLedgerExportRequest(BaseModel):
    """信访台账导出请求模型"""
    region: Optional[str] = None
    petitioner_name: Optional[str] = None
    respondent_unit: Optional[str] = None
    analysis_status: Optional[str] = None
    date_from: Optional[str] = None
    date_to: Optional[str] = None
    sentiment_type: Optional[str] = None
    complaint_type: Optional[str] = None
    task_id: Optional[int] = None
    export_format: str = "excel"  # excel, csv, json

@router.get("/petition-ledger/")
async def get_petition_ledger_list(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    region: Optional[str] = None,
    petitioner_name: Optional[str] = None,
    respondent_unit: Optional[str] = None,
    analysis_status: Optional[str] = None,
    date_from: Optional[str] = None,
    date_to: Optional[str] = None,
    sentiment_type: Optional[str] = None,
    complaint_type: Optional[str] = None,
    task_id: Optional[int] = None,
    has_duplicates: Optional[str] = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取信访台账列表
    """
    try:
        service = PetitionLedgerService(db)
        result = service.get_petition_ledger_list(
            page=page,
            page_size=page_size,
            region=region,
            petitioner_name=petitioner_name,
            respondent_unit=respondent_unit,
            analysis_status=analysis_status,
            date_from=date_from,
            date_to=date_to,
            sentiment_type=sentiment_type,
            complaint_type=complaint_type,
            task_id=task_id,
            has_duplicates=has_duplicates
        )

        return {
            "code": 200,
            "message": "success",
            "data": result["items"],
            "pagination": {
                "total": result["total"],
                "page": result["page"],
                "page_size": result["page_size"],
                "total_pages": result["total_pages"]
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/petition-ledger/{record_id}")
async def get_petition_ledger_detail(
    record_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取信访台账详情
    """
    try:
        service = PetitionLedgerService(db)
        result = service.get_petition_ledger_detail(record_id)

        return {
            "code": 200,
            "message": "success",
            "data": result
        }
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/petition-ledger/export")
async def export_petition_ledger(
    export_params: PetitionLedgerExportRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    导出信访台账数据
    """
    try:
        service = PetitionLedgerService(db)
        file_path = service.export_petition_ledger(export_params.dict())

        return {
            "code": 200,
            "message": "success",
            "data": {
                "file_path": file_path,
                "download_url": f"/api/petition-ledger/download/{file_path.split('/')[-1]}"
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/petition-ledger/statistics/summary")
async def get_petition_ledger_summary(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取信访台账统计摘要
    """
    try:
        service = PetitionLedgerService(db)
        result = service.get_petition_ledger_summary()

        return {
            "code": 200,
            "message": "success",
            "data": result
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))